package com.hangzhou.xyj.ui.activity;

import android.content.Intent;
import android.view.View;
import android.widget.EditText;

import com.hangzhou.xyj.R;
import com.hangzhou.xyj.XYJApplication;
import com.hangzhou.xyj.db.RecordDao;
import com.hangzhou.xyj.manager.IntentManager;
import com.hangzhou.xyj.model.RecordModel;
import com.hangzhou.xyj.model.XXLocation;
import com.hangzhou.xyj.net.handler.AddDynamicHandler;
import com.hangzhou.xyj.net.http.HttpLoader;
import com.hangzhou.xyj.net.okhttp.listener.impl.UIProgressListener;
import com.hangzhou.xyj.net.request.AddDynamicReq;
import com.hangzhou.xyj.net.response.base.BaseResponse;
import com.hangzhou.xyj.ui.activity.base.BaseActivity;
import com.hangzhou.xyj.ui.dialog.InputDramaNameDialog;
import com.hangzhou.xyj.ui.dialog.TipsDialog;
import com.hangzhou.xyj.ui.widget.CommonTitleBarView;
import com.hangzhou.xyj.ui.widget.multiimageselector.utils.TimeUtils;
import com.hangzhou.xyj.utils.LogUtil;
import com.hangzhou.xyj.utils.StringUtil;
import com.hangzhou.xyj.utils.ToastUtil;
import com.hangzhou.xyj.utils.constants.DataKey;

/**
 * Created by neo.duan on 2016/1/16.
 * 发布录制
 */
public class PublishRecordActivity extends BaseActivity {
    private EditText mEdtInput;
    private RecordModel mRecordModel; //戏曲数据结构

    @Override
    public void initTop() {
        enableTitle(true, "上传到我动态");
        enableRightNav(true, "确定");
        setOnNavRightListener(new CommonTitleBarView.OnNavRightListener() {
            @Override
            public void onNavRight() {
                if (!checkInput()) {
                    return;
                }
                if (StringUtil.isBlank(mRecordModel.getName())) {
                    showInputDramaNameDialog();
                    return;
                }
//                //上传文件
                if (StringUtil.isBlank(mRecordModel.getMixerFilePath())) {
                    ToastUtil.show("音频文件路径为空");
                    return;
                }
                uploadFile(mRecordModel.getMixerFilePath());
            }
        });
    }

    @Override
    public void initIntentData(Intent intent) {
        mRecordModel = (RecordModel) intent.getSerializableExtra(DataKey.DRAMA);
    }

    @Override
    public void initLayouts() {
        setContentView(R.layout.activity_publish_record);
    }

    @Override
    public void initViews() {
        mEdtInput = findView(R.id.et_input);
    }

    @Override
    public void initDatas() {

    }

    @Override
    public void initListeners() {

    }

    /**
     * 校验输入值
     *
     * @return
     */
    private boolean checkInput() {
        String text = mEdtInput.getText().toString().trim();
        if (StringUtil.isBlank(text)) {
            ToastUtil.show("内容输入为空");
            return false;
        }
        return true;
    }

    /**
     * 上传混音文件到服务器
     *
     * @param fileName
     */
    protected void uploadFile(String fileName) {
        HttpLoader.getInstance().uploadFile(fileName, new UIProgressListener() {
            @Override
            public void onUIStart() {
                super.onUIStart();
                showLoadingDialog(0);
            }

            @Override
            public void onUIProgress(long currentBytes, long contentLength, boolean done) {
                int progress = (int) ((100 * currentBytes) / contentLength);
                LogUtil.d(TAG, "progress:  " + progress);
                showLoadingDialog(progress);
            }

            @Override
            public void onUIFinish(BaseResponse response) {
                super.onUIFinish(response);
                LogUtil.d(TAG, response.toString());
                if (response.isSuccess()) {
                    //上传成功:发布动态
                    mRecordModel.setNativeUrl(response.getData().toString());
                    publishDynamic();
                } else {
                    LogUtil.e(TAG, response.getMsg());
                }
                hideLoadingDialog();
            }
        });
    }

    /**
     * 发布动态
     */
    private void publishDynamic() {
//       public AddDynamicReq(int type, String userId,int baseDramaId, String dramaName,
//        String dramaUrl, String lrcUrl,String time, String content,
//                String address, String city) {
        //定位成功，地址放入定位地址
        String address = "";
        String city = XYJApplication.getUserInfo().getZone();
        XXLocation location = XYJApplication.getInstance().getLocation();
        if (location != null) {
            address = location.getAddress();
        }

        AddDynamicReq req = new AddDynamicReq(
                AddDynamicReq.TYPE_AUDIO,
                XYJApplication.getUserInfo().getUserId(),
                mRecordModel.getId(),
                mRecordModel.getName(),
                mRecordModel.getNativeUrl(),
                mRecordModel.getLrcUrl(),
                TimeUtils.timeFormat(mRecordModel.getDuration(), "mm:ss"),
                mEdtInput.getText().toString().trim(),
                address,   //详细地址，默认空
                city);

        //请求发布动态
        HttpLoader.getInstance().sendRequest(new AddDynamicHandler(req, new MyHttpResponseListener() {
            @Override
            public void onSuccess(Object model) {
                super.onSuccess(model);
                //发布成功,保存为本地标记为已上传，并弹出对话框跳转
                RecordDao dao = new RecordDao(mContext);
                mRecordModel.setIsUpload(true);
                dao.addDrama(mRecordModel);
                showSuccessDialog();
            }
        }, 0));
    }

    /**
     * 显示界面，如果戏曲名称为空，则弹出输入歌曲名称
     */
    @Override
    protected void onResume() {
        super.onResume();
//        if (StringUtil.isBlank(mRecordModel.getName())) {
//            showInputDramaNameDialog();
//        }
    }

    /**
     * 弹出输入歌曲名称对话框
     */
    private void showInputDramaNameDialog() {
        final InputDramaNameDialog dialog = new InputDramaNameDialog(mContext);
        dialog.setNegativeListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //取消
                dialog.dismiss();
            }
        });
        dialog.setPositiveListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //确定
                mRecordModel.setName(dialog.getDramaName());
                dialog.dismiss();
                //上传文件
                if (StringUtil.isBlank(mRecordModel.getMixerFilePath())) {
                    ToastUtil.show("音频文件路径为空");
                    return;
                }
                uploadFile(mRecordModel.getMixerFilePath());
            }
        });
        dialog.show();
    }

    /**
     * 弹出发布成功对话框
     */
    private void showSuccessDialog() {
        TipsDialog dialog = new TipsDialog(mContext, "上传成功", "可以到我的动态页面查看", "现在查看", "以后再说") {
            //以后再说
            @Override
            protected void OnClickNegativeButton() {
                closeActivity();
                this.dismiss();
            }

            //现在查看
            @Override
            protected boolean OnClickPositiveButton() {
                //TODO 跳转到我的录音界面:先调到我的动态页面
                IntentManager.getInstance().goMyActiveActivity(mContext);
                closeActivity();
                this.dismiss();
                return true;
            }
        };
        dialog.show();
    }

}
